package cl.solidit.geomanagement.web.controller;

import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

import org.codehaus.jackson.map.ObjectMapper;
import org.hibernate.Hibernate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cl.solidit.geomanagement.persistance.PersonaDAO;
import cl.solidit.geomanagement.persistance.UserDAO;
import cl.solidit.geomanagement.persistance.VisitaDAO;
import cl.solidit.geomanagement.persistance.model.Persona;
import cl.solidit.geomanagement.persistance.model.Propiedad;
import cl.solidit.geomanagement.persistance.model.Usuario;
import cl.solidit.geomanagement.persistance.util.Rut;
import cl.solidit.geomanagement.web.controller.comunication.JSONUser;

@Controller
public class ConsultarPersonaController {

	private static final Logger logger = LoggerFactory
			.getLogger(ConsultarPersonaController.class);

	@Autowired
	private PersonaDAO personaDAO;
	@Autowired
	private UserDAO userDAO;
	@Autowired
	private VisitaDAO visitaDAO;

	@RequestMapping(value = "/consultar_cliente/{id}", method = RequestMethod.GET)
	@Transactional
	public ModelAndView consultarClienteGet(@PathVariable Long id) {

		Persona persona = personaDAO.findById(id);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("persona", persona);
		for (Propiedad p : persona.getPropiedades()) {
			Hibernate.initialize(p.getEstado());
			Hibernate.initialize(p.getComuna());

		}

		Hibernate.initialize(persona.getComuna());

		return new ModelAndView("consultar_cliente", map);

	}

	@RequestMapping(value = "/consultar_cliente", method = RequestMethod.POST)
	public String consultarPropiedad(
			@ModelAttribute("modeloPersona") Persona persona, ModelMap modelo) {
		modelo.get(persona);
		return "consultarCliente";
	}

	@RequestMapping(value = "/consultar_propietario/{id}", method = RequestMethod.GET)
	@Transactional
	public ModelAndView consultarPropietarioGet(@PathVariable Long id) {

		Persona persona = personaDAO.findById(id);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("persona", persona);
		for (Propiedad p : persona.getPropiedades()) {
			Hibernate.initialize(p.getEstado());
			Hibernate.initialize(p.getComuna());

		}

		Hibernate.initialize(persona.getComuna());

		return new ModelAndView("consultar_propietario", map);

	}

	@Transactional
	@RequestMapping(value = "/consultar_usuario/{id}", method = RequestMethod.GET)
	public ModelAndView acceso(@PathVariable Long id) {

		Usuario usuario = userDAO.findById(id);
		Map<String, Object> map = new HashMap<String, Object>();

		Hibernate.initialize(usuario.getPersona());
		Hibernate.initialize(usuario.getPersona().getComuna());
		map.put("usuario", usuario);

		return new ModelAndView("consultar_usuario", map);

	}

	@RequestMapping(value = "/consultar_usuario", method = RequestMethod.POST)
	public String consultarPropiedad(Usuario usuario, ModelMap modelo) {
		modelo.get(usuario);

		return "consultar_usuario";
	}

	@Transactional
	@RequestMapping(value = "/search_persona", method = { RequestMethod.GET,
			RequestMethod.POST }, produces = "application/json; charset=utf-8")
	public @ResponseBody String searchPersona(
			@RequestParam(value = "rut") String rut) {
		if (!Rut.validate(rut)) {
			return "";
		}
		Persona p = personaDAO.findByRut(rut);
		if (p == null)
			return "{}";
		JSONUser jsonUser = new JSONUser(p);
		StringWriter writer = new StringWriter();
		String result = "{}";
		try {
			new ObjectMapper().writeValue(writer, jsonUser);
			writer.flush();
			result = writer.toString();
			// System.out.println(result.s);
			writer.close();
		} catch (Exception e) {
			logger.error("No se pudo serializar las personas", e);
		}
		return result;
	}

	@Transactional
	@RequestMapping(value = "/search_persona_apellido", method = {
			RequestMethod.GET, RequestMethod.POST }, produces = "application/json; charset=utf-8")
	public @ResponseBody String searchPersonaByApellido(
			@RequestParam(value = "apellido") String apellido) {

		Persona p = personaDAO.findByApellido(apellido);
		if (p == null)
			return "{}";
		JSONUser jsonUser = new JSONUser(p);
		StringWriter writer = new StringWriter();
		String result = "{}";
		try {
			new ObjectMapper().writeValue(writer, jsonUser);
			writer.flush();
			result = writer.toString();
			// System.out.println(result.s);
			writer.close();
		} catch (Exception e) {
			logger.error("No se pudo serializar las personas", e);
		}
		return result;
	}

}
